<template>
  <el-upload
    class="upload-demo"
    action=""
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList"
    list-type="picture"
    :before-upload="beforeUpload"
  >
    <el-button size="small" type="primary" v-if="flagLimit">点击上传</el-button>
    <div slot="tip" class="el-upload__tip" v-if="flagLimit">
      只能上传jpg/png文件，且不超过500kb
    </div>
  </el-upload>
</template>

<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
import { reqYczsInfoType } from "CustomTypes";
import { getImgsTempUrl, getApp } from "@/utils/cloud";
import { isUndefined, concat, isEqual } from "lodash";
import { Message } from "element-ui";

@Component({
  name: "PictureWall"
})
export default class PictureWall extends Vue {
  @Prop()
  private limit?: number;
  get flagLimit() {
    // 如果没有定义限制数量，那么就显示
    if (isUndefined(this.limit)) {
      return true;
    }
    // 如果定义了限制数量
    else {
      /**
       * 检查当前已经有的图片的数量，
       * 如果大于或者等于限制，那么就不显示。
       */
      return !(this.fileList.length >= this.limit);
    }
  }
  hasOptions = false;
  fileListSubmit: Array<string> = [];
  /**
   * 注意这里不能使用 private
   * 而且这里存储的都是临时下载地址。
   */
  fileList: Array<{ name: string; url: string }> = [];

  beforeUpload(file: any) {
    const app = getApp();
    const reader = new FileReader();

    reader.readAsDataURL(file);
    reader.onloadend = () => {
      const cloudPath = `${
        process.env.VUE_APP_PICTURE_UPLOAD_URL
      }/${new Date().valueOf()}_${file.name}`;

      app
        .uploadFile({
          cloudPath,
          filePath: file
        })
        .then(async (res: any) => {
          if (isUndefined(res)) return false;
          this.hasOptions = true;

          // 这里得到的fileID是存储地址。这个地址是要记录在数据库中的。
          this.fileListSubmit.push(res.fileID);

          // 立刻获取图片的临时下载地址
          const { fileList } = await getImgsTempUrl([res.fileID]);
          const tempFileList = fileList.map((file: any) => ({
            name: file.name,
            url: file.url
          }));

          // 这样的赋值，用于预览。
          this.fileList = concat(this.fileList, tempFileList);

          // 表示已经修改
          this.hasOptions = true;

          Message.success("图片缓存成功");
        })
        .catch((err: any) => {
          console.log("图片上传错误", err);
        });
    };

    return true;
  }

  handlePreview(file: any) {
    console.log(file);
  }

  handleRemove(file: any, fileList: Array<any>) {
    // file {name:照片的名字,status:"success",uid:数字,url:临时下载地址}
    // fileList 等于 []
    // console.log(file, fileList);
    this.fileListSubmit = fileList;
    this.hasOptions = true;
  }
}
</script>

<style>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}
</style>
